from typing import List, Optional, Tuple
from sqlalchemy.orm import Session
from sqlalchemy import or_
from app.models.technology_tag import TechnologyTag
from app.schemas.technology_tag import TechnologyTagCreate, TechnologyTagUpdate, TechnologyTagFilter

def get_technology_tag(db: Session, tag_id: int) -> Optional[TechnologyTag]:
    return db.query(TechnologyTag).filter(TechnologyTag.id == tag_id).first()

def get_technology_tag_by_name(db: Session, name: str) -> Optional[TechnologyTag]:
    return db.query(TechnologyTag).filter(TechnologyTag.name == name).first()

def get_all_technology_tags(db: Session) -> List[TechnologyTag]:
    """
    获取所有技术方向标签，不分页
    """
    return db.query(TechnologyTag).all()

def get_technology_tags(
    db: Session,
    filter_params: TechnologyTagFilter
) -> Tuple[List[TechnologyTag], int]:
    query = db.query(TechnologyTag)
    
    # 应用过滤条件
    if filter_params.name:
        query = query.filter(TechnologyTag.name == filter_params.name)
    if filter_params.search:
        search = f"%{filter_params.search}%"
        query = query.filter(
            or_(
                TechnologyTag.name.ilike(search),
                TechnologyTag.description.ilike(search),
                TechnologyTag.remark.ilike(search)
            )
        )
    
    # 获取总数
    total = query.count()
    
    # 应用分页
    query = query.offset((filter_params.page - 1) * filter_params.page_size)\
                .limit(filter_params.page_size)
    
    return query.all(), total

def create_technology_tag(
    db: Session,
    tag: TechnologyTagCreate
) -> TechnologyTag:
    db_tag = TechnologyTag(**tag.model_dump())
    db.add(db_tag)
    db.commit()
    db.refresh(db_tag)
    return db_tag

def update_technology_tag(
    db: Session,
    tag_id: int,
    tag: TechnologyTagUpdate
) -> Optional[TechnologyTag]:
    db_tag = get_technology_tag(db, tag_id)
    if not db_tag:
        return None
    
    update_data = tag.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_tag, field, value)
    
    db.commit()
    db.refresh(db_tag)
    return db_tag

def delete_technology_tag(db: Session, tag_id: int) -> bool:
    db_tag = get_technology_tag(db, tag_id)
    if not db_tag:
        return False
    
    db.delete(db_tag)
    db.commit()
    return True 